
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

import '../utils/local_storage.dart';

typedef OnSelectedDate = void Function(String date);

/// 更新设备位置
class UpdateLocation extends StatefulWidget {
  UpdateLocation(
      {required this.onSelectedValue,
        this.selectedValue = "",
        required this.yearList,
      });

  // 结果返回
  final OnSelectedDate onSelectedValue;
  final String selectedValue; //选中的时间
  List<Map<String, String>> yearList = [];
  
  @override
  _UpdateLocationState createState() => _UpdateLocationState();
}

class _UpdateLocationState extends State<UpdateLocation> {

  List<Map<String, String>> monthList = [];
  
  //年的索引
  int yearIndex = 0;
  //月的索引
  int monthIndex = 0;
  //每列的宽度
  double _columnWidth = 0;

  FixedExtentScrollController yearScrollController = FixedExtentScrollController();
  FixedExtentScrollController monthScrollController = FixedExtentScrollController();

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    super.initState();

    _columnWidth = MainCommon.screenWidth / 2;

    _initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController.dispose();
    monthScrollController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _headerWidget(),
          _datePicker(),
        ],
      ),
    );
  }

  ///初始化时间索引
  void _initSelectedIndex() {
    setState(() {
      yearIndex = 0;
      monthIndex = 0;
    });

    final floorId = widget.yearList[yearIndex]["id"] ?? "";
    _getRoomInfo(floorId);

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    monthScrollController =
        FixedExtentScrollController(initialItem: monthIndex);
  }

  Widget _headerWidget() {
    return Container(
      height: 60,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            TextButton(
              child: Text(
                LocaleKeys.login_cancel.trc(),
                style: TextStyle(
                  fontSize: 16.0,
                  color: isDarkMode ? Colors.white : Colors.black
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: Text(
                LocaleKeys.add_device_confirm.trc(),
                style: TextStyle(
                  fontSize: 16.0,
                  color: isDarkMode ? Colors.white : Colors.black
                ),
              ),
              onPressed: () {
                if (widget.onSelectedValue != null) {
                  final floorMap = widget.yearList[yearIndex];
                  final roomMap = monthList[monthIndex];

                  String date = roomMap["id"] ?? "";
                  widget.onSelectedValue(date);
                }
              },
            ),
          ]),
      decoration: BoxDecoration(
        border: Border(
            bottom: BorderSide(color: Colors.grey.withOpacity(0.1), width: 1)),
      ),
    );
  }

  Widget _datePicker() {
    return Container(
      color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
      height: 200,
      child: Stack(
        children: [
          Row(
            children: <Widget>[
              Expanded(child: _yearPickerView()),
              Expanded(child: _monthPickerView()),
            ],
          ),
          Container(
            color: Color(0xFFD1D1D6),
            margin: EdgeInsets.only(top: 78),
            height: 1,
          ),
          Container(
            color: Color(0xFFD1D1D6),
            margin: EdgeInsets.only(top: 124),
            height: 1,
          ),
          Container(
            margin: EdgeInsets.only(top: 78),
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: _columnWidth - 40, top: 9),
                    child: Text(
                      '',
                      style: TextStyle(fontSize: 16),  // color: Colors.grey,
                      maxLines: 1,
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: _columnWidth - 50, top: 9),
                    child: Text(
                      '',
                      style: TextStyle(fontSize: 16),  // color: Colors.grey,
                      maxLines: 1,
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: _columnWidth - 50, top: 9),
                    child: Text(
                      '',
                      style: TextStyle(fontSize: 16),  // color: Colors.grey,
                      maxLines: 1,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///年
  Widget _yearPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: yearScrollController,
        children: _buildYearWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            yearIndex = index;
            _getRoomInfo(widget.yearList[index]["id"] ?? "");
          });
        },
        itemExtent: 44,
      ),
    );
  }

  ///月
  Widget _monthPickerView() {
    return Container(
      child: CupertinoPicker(
        scrollController: monthScrollController,
        children: _buildMonthWidget(),
        looping: false,
        selectionOverlay: Center(),
        onSelectedItemChanged: (index) {
          setState(() {
            monthIndex = index;
          });
        },
        itemExtent: 44,
      ),
    );
  }

  ///年Widget
  List<Widget> _buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in widget.yearList) {
      yearListWidget.add(
        new Center(
          child: Text(
            item["name"] ?? "",
            style: TextStyle(color: isDarkMode ? Colors.white : Colors.black87, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> _buildMonthWidget() {
    List<Widget> monthListWidget = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in monthList) {
      monthListWidget.add(
        new Center(
          child: Text(
            item["name"] ?? "",
            style: TextStyle(color: isDarkMode ? Colors.white : Colors.black87, fontSize: 16),
            maxLines: 1,
          ),
        ),
      );
    }

    return monthListWidget;
  }

  // 获取楼层数据
  _getRoomInfo(String floorId) async {
    ResultData data = await AppApi.getInstance().getHallInfo({"floorId": "$floorId"});
    if(data.code == 0){
      final list = data.data as List;
      monthList = list.map((e) => {"id": e["id"].toString(), "name": e["name"].toString()}).toList();
      setState(() {});
    }else {
      SmartDialog.showToast(data.msg);
    }
  }
  

}